package com.tbynet.jwp.admin.attachment;

import java.awt.image.BufferedImage;
import java.io.File;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.imageio.ImageIO;

import com.jfinal.aop.Inject;
import com.jfinal.core.JFinal;
import com.jfinal.kit.Kv;
import com.jfinal.kit.Ret;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.upload.UploadFile;
import com.tbynet.jwp.admin.AdminController;
import com.tbynet.jwp.framework.kit.DateKit;
import com.tbynet.jwp.framework.kit.StringKit;
import com.tbynet.jwp.model.Options;
import com.tbynet.jwp.model.Postmeta;
import com.tbynet.jwp.model.Posts;
import com.tbynet.jwp.service.CommentService;
import com.tbynet.jwp.service.OptionService;
import com.tbynet.jwp.service.PostService;
import com.tbynet.jwp.service.UserService;

import net.coobird.thumbnailator.Thumbnails;

public class AttachmentAdminController extends AdminController {

	@Inject
	PostService postService;
	
	@Inject
	OptionService optionService;

	@Inject
	UserService userService;

	@Inject
	CommentService commentService;
	
	public void index() {
		render("index.html");
	}
	
	public void search() throws Exception {
		String q = getPara("q");
		
		Page<Posts> page = postService.search(getPage(), getSize(), Posts.POST_TYPE_ATTACHMENT, null, q);
		for(Posts post : page.getList()) {
			Postmeta wpAttachedfile = postService.getPostmeta(post.getID(), Postmeta._wp_attached_file);
			post.put("filename", null == wpAttachedfile ? "" : wpAttachedfile.getMetaValue());
			post.put("author", userService.getUser(post.getPostAuthor()));
			post.put("comments", commentService.count(post.getID()));
			post.put("post_modified_format", DateKit.format(post.getPostModified(), "yyyy-MM-dd"));
		}
		
		ok(Ret.by("data", page));
	}
	
	public void create() {
		render("create.html");
	}
	
	public void edit() {
		Posts post = postService.getPost(getPara("post"), Posts.POST_TYPE_ATTACHMENT);
		
		set("post", post);
		render("edit.html");
	}
	
	public void save() throws Exception {
		//定义存储目录方式
		String path = "/";
		String uploads_use_yearmonth_folders = optionService.getOption(Options.uploads_use_yearmonth_folders).getOptionValue();
		if(null != uploads_use_yearmonth_folders && "0" != uploads_use_yearmonth_folders) {
			path = DateKit.toStr(new Date(), "yyyy") + File.separator + DateKit.toStr(new Date(), "MM");
		}

		String siteurl = optionService.getOption(Options.siteurl).getOptionValue();
		UploadFile uf = getFile("file", path);
		
		File file = uf.getFile();
		String fileName = uf.getFileName();
		String name = fileName.substring(0, fileName.lastIndexOf("."));//图片名称，不包括后缀
		String suffix = fileName.substring(fileName.lastIndexOf("."));//图片后缀名
		
		//附件
		Posts post = new Posts();
		post.setPostType(Posts.POST_TYPE_ATTACHMENT);
		post.setPostStatus(Posts.POST_STATUS_INHERIT);
		post.setPostTitle(name);
		post.setPostName(StringKit.urlencode(name));
		post.setPostMimeType(uf.getContentType());
		post.setPostParent(new BigInteger(getPara("post_parent", "0")));
		post.setGuid(siteurl + File.separator + JFinal.me().getConstants().getBaseUploadPath() + File.separator + path + File.separator + uf.getFileName());//path
		post.setPostContent("");
		post.setPostContentFiltered("");
		post.setPostExcerpt("");
		post.setToPing("");
		post.setPinged("");
		post.setCommentStatus("closed");
		post.setPingStatus("closed");
		post.setMenuOrder(0);
		post.setCommentCount(0l);
		post.setPostAuthor(new BigInteger(getPara("post_author")));
		post.setPostDate(new Date(System.currentTimeMillis()));
		post.setPostDateGmt(new Date(System.currentTimeMillis()));
		post.setPostModified(new Date(System.currentTimeMillis()));
		post.setPostModifiedGmt(new Date(System.currentTimeMillis()));
		
		//附件元数据
		List<Postmeta> postmetas = new ArrayList<Postmeta>();
		
		//_wp_attached_file
		Postmeta wpAttachedFile = new Postmeta();
		wpAttachedFile.setWpAttachedFile(path + File.separator + uf.getFileName());
		postmetas.add(wpAttachedFile);
		
		BufferedImage image = ImageIO.read(file);//注意：该方法适用的图片格式为 bmp/gif/jpg/png
		if(null != image) {
			int width = image.getWidth();//图片宽度
			int height = image.getHeight();//图片高度
			
			//_wp_attachment_metadata
			Postmeta wpAttachmentMetadata = new Postmeta();
			
			Kv kv = Kv.by("width", width).set("height", height).set("file", fileName);
			
			//定义各缩略图尺寸
			Kv sizes = Kv.create();
			
			//生成默认尺寸的缩略图
			String thumbnailCrop = optionService.getOption(Options.thumbnail_crop).getOptionValue();
			int thumbnailSizeW = Integer.valueOf(optionService.getOption(Options.thumbnail_size_w).getOptionValue());
			int thumbnailSizeH = Integer.valueOf(optionService.getOption(Options.thumbnail_size_h).getOptionValue());
			if((StrKit.notBlank(thumbnailCrop) && "1".equals(thumbnailCrop)) 
					|| width > thumbnailSizeW || height > thumbnailSizeH) {
				fileName = name + "-" + thumbnailSizeW + "x" + thumbnailSizeH + suffix;
				Thumbnails.of(file).width(thumbnailSizeW).height(thumbnailSizeH).toFile(new File(uf.getUploadPath() + File.separator + fileName));
				
				Kv thumbnail = Kv.by("file", fileName).set("width", thumbnailSizeW)
						.set("height", thumbnailSizeH).set("mime-type", uf.getContentType());
				
				sizes.set("thumbnail", thumbnail);
			}
			
			//生成中尺寸的缩略图
			int mediumSizeW = Integer.valueOf(optionService.getOption(Options.medium_size_w).getOptionValue());
			int mediumSizeH = Integer.valueOf(optionService.getOption(Options.medium_size_h).getOptionValue());
			if(width > mediumSizeW || height > mediumSizeH) {
				fileName = name + "-" + mediumSizeW + "x" + mediumSizeH + suffix;
				Thumbnails.of(file).width(mediumSizeW).height(mediumSizeH).toFile(new File(uf.getUploadPath() + File.separator + fileName));
				
				Kv medium = Kv.by("file", fileName).set("width", mediumSizeW)
						.set("height", mediumSizeH).set("mime-type", uf.getContentType());
				
				sizes.set("medium", medium);
			}
			
			//生成大尺寸的缩略图
			int largeSizeW = Integer.valueOf(optionService.getOption(Options.large_size_w).getOptionValue());
			int largeSizeH = Integer.valueOf(optionService.getOption(Options.large_size_h).getOptionValue());
			if(width > largeSizeW || height > largeSizeH) {
				fileName = name + "-" + largeSizeW + "x" + largeSizeH + suffix;
				Thumbnails.of(file).width(largeSizeW).height(largeSizeH).toFile(new File(uf.getUploadPath() + File.separator + fileName));
				
				Kv large = Kv.by("file", fileName).set("width", largeSizeW)
						.set("height", largeSizeH).set("mime-type", uf.getContentType());
				
				sizes.set("large", large);
			}
			
			kv.set("sizes", sizes);
			
			//这里的参数需要用第三方框架获取
			Kv imageMeta = Kv.by("aperture", "0").set("credit", "0").set("camera", "0")
					.set("caption", "0").set("created_timestamp", "0").set("copyright", "0").set("focal_length", "0")
					.set("iso", "0").set("shutter_speed", "0").set("title", "0").set("orientation", "0")
					.set("keywords", Kv.create());
			
			kv.set("image_meta", imageMeta);
			
			wpAttachmentMetadata.setWpAttachmentMetadata(kv);
			postmetas.add(wpAttachmentMetadata);
		} else {
			Postmeta editLock = new Postmeta();
			editLock.setMetaKey(Postmeta._edit_lock);
			editLock.setMetaValue(new Date().getTime() + ":" + 1);
			postmetas.add(editLock);
		}
		
		if(postService.save(post, postmetas)) {
			ok(Ret.by("data", post));
		} else {
			fail("上传文件失败，请联系管理员");
		}
	}

	public void update() {
		
	}
	
	public void delete() {
		
	}
	
	public void finder() {
		
		render("finder.html");
	}
}
